package com.changgou.consume.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.consume.config.RabbitMQConfig;
import com.changgou.consume.service.SeckillOrderService;
import com.changgou.seckill.pojo.SeckillOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wz
 * @company 公司
 * @create 2020-04-20 16:30
 */
@Component
public class ConsumeListener {

    @Autowired
    private SeckillOrderService seckillOrderService;


    @RabbitListener(queues = RabbitMQConfig.SECKILL_ORDER_QUUEU)
    public void receiveSecKillOrderMessage(Message message, Channel channel) {


        //设置预抓取总数
        try {
            channel.basicQos(300);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //1.转换消息格式
        SeckillOrder seckillOrder = JSON.parseObject(message.getBody(), SeckillOrder.class);
        //2.基于业务层完成同步mysql的操作
        int result = seckillOrderService.createOrder(seckillOrder);
        if (result>0){
            //同步mysql成功
            //向消息服务器返回成功的通知
            try {
                //消息唯一标识  是否开启批处理
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //同步mysql失败
            //向消息服务器返回失败的通知
            try {
                //1.消息的唯一标识
                //2.true所有的消费者拒接这个消息  false只有当前消费者拒绝此消息
                //3.true只要当前的消息会进入到死信队列中  false当前消息会从新进入到原有队列中，默认回到头部
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
